package com.haiheng.module_main.adapter.bookcar

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import com.haiheng.library_base.adapter.BaseAdapter
import com.haiheng.library_base.db.BookInfoBean
import com.haiheng.library_base.toast.SizeUtils
import com.haiheng.library_base.view.shape.ShadowDrawable
import com.haiheng.module_main.R
import com.haiheng.module_main.bean.res.bookcar.BookCarBookResult
import com.haiheng.module_main.databinding.ItemBookCarListBinding
import com.haiheng.module_main.databinding.ItemBookCarShelfBinding

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2024/8/20 0020
 * @Version: 1.0
 */
class BookCarShelfAdapter(
    private val onBookSelected: (BookCarBookResult) -> Unit
) : BaseAdapter<Pair<String, List<BookCarBookResult>>>() {

    override fun onCreateViewBinding(viewType: Int): (LayoutInflater, ViewGroup, Boolean) -> ViewBinding {
        // 为每个科室创建一个包含子RecyclerView的布局
        return ItemBookCarShelfBinding::inflate
    }

    override fun onItemView(holder: ViewBindHolder, position: Int, item: Pair<String, List<BookCarBookResult>>) {
        val binding = holder.binding as ItemBookCarShelfBinding
        ShadowDrawable.setShadowDrawable(binding.itemview,
            holder.itemView.context.getColor(R.color.white),
            SizeUtils.dp2px(10f),
            holder.itemView.context.getColor(R.color.color_330071FF)
            , SizeUtils.dp2px(4f), 0, 0)
        // 设置科室名称
        binding.tvDepartment.text = item.first

        // 设置图书RecyclerView的适配器
        val bookAdapter = BookCarAdapter(onBookSelected)
        binding?.rvBookList?.layoutManager = LinearLayoutManager(holder.itemView.context)
        binding.rvBookList.adapter = bookAdapter
        bookAdapter.setNewData(item.second)

        // 控制展开与收起
        binding.tvExpand.setOnClickListener {
            val isVisible = binding.rvBookList.visibility == View.VISIBLE
            binding.rvBookList.visibility = if (isVisible) View.GONE else View.VISIBLE
            binding.tvExpand.setText(if (isVisible) "展开" else "收起")
        }
    }

    override fun getItemCount(): Int {
        return getData().size
    }

    // 更新数据
    fun updateData(newData: Map<String, List<BookCarBookResult>>) {
        val newList = newData.entries.map { it.key to it.value }
        newData.entries.firstOrNull()?.let { (key, value) ->
            // 检查列表是否非空，并且至少有一个元素
            if (value.isNotEmpty()) {
                // 更新列表的第一个元素
                var b = value[0]
                b.isSelect =true
            }
        }
        setNewData(newList)
    }

    // 方法：获取所有被选中的书籍
    fun getSelectedBooks(): List<BookCarBookResult> {
        return getData().flatMap { (key, books) ->
            books.filter { it.isSelect }
        }
    }


}
